import pandas as pd
import numpy as np
from datetime import datetime

# 读取Excel文件并转化日期格式
df = pd.read_excel('ymData.xlsx')
df['date'] = pd.to_datetime(df['date'],format='%Y年%m月')

# 使用 strftime 将 Timestamp 转换为字符串类型
df['date'] = df['date'].dt.strftime('%y年%m月').tolist()
# 2. 将dataframe中的数据类型从str转换为datetime类型
from datetime import *
df['date'] = df['date'].map(lambda x: datetime.strptime(x, "%y年%m月"))
df['date']


# 3. 使用map()或apply()函数对日期特征进行年、月、日的提取

df["year"] = df["date"].map(lambda x: x.year)
df["month"] = df["date"].map(lambda x: x.month)
df

# 将特征和标签分开

X = df[['year', 'month']].values
y = df["date"].values



# 划分数据集
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)

# 建立贝叶斯分类器
from sklearn.naive_bayes import MultinomialNB
classifier = MultinomialNB()
classifier.fit(X_train, y_train)

# 预测测试集
y_pred = classifier.predict(X_test)

# 计算准确度、召回率、F1值等指标
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
accuracy = accuracy_score(y_test, y_pred)
precision = precision_score(y_test, y_pred,average='weighted')
recall = recall_score(y_test, y_pred,average='weighted')
f1 = f1_score(y_test, y_pred,average='weighted')
print('Accuracy:', accuracy)
print('Precision:', precision)
print('Recall:', recall)
print('F1 score:', f1)
